<?php
namespace app\mos\controller;
use Alipay\Alipayobj;
use app\common\model\Agent;
use app\common\model\CardGeneral;
use app\common\model\CardMemberAli;
use app\common\model\System;
use app\common\model\WxOpen;
use app\common\model\Merchant;
use app\common\model\CardMember;
use think\Session;
use think\Controller;
use Wechat\Wxobjopen;

class Mobileali extends Controller
{

    //获取授权
    /*
     * $card_id
     *
     */
    public function _init()
    {
        //初始化
//        $datas['merchid'] = request()->get('mid');
        $mid = 501;
        $datas['merchid'] = $mid;
        $User = new Merchant();
        $Agent = new Agent();
        $users = $User->where(array('id' => $datas['merchid']))->find();
        $agent = $Agent->where(array('id' => $users['agent']))->find();
        $options = array(
            'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
            'rsaPrivateKey' => $agent['ali_app_key'],
        );
        $aliObj = new Alipayobj($options);
        if (request()->get('auth_code')) {
            //参数
            $data['app_id'] = $agent['ali_app_id'];
            $data['method'] = "alipay.system.oauth.token";
            $data['charset'] = "UTF-8";
            $data['sign_type'] = "RSA2";
            $data['timestamp'] = date('Y-m-d H:i:s');
            $data['version'] = "1.0";
//            $data['app_auth_token'] = $users['ali_merid'];
            $data['grant_type'] = 'authorization_code';
            $data['code'] = request()->get('auth_code');
            $signContent = $aliObj->rsaSign($data, $signType = "RSA2");
            $data['sign'] = $signContent;
//            var_dump(json_encode($data,JSON_UNESCAPED_UNICODE));
            $uid = $aliObj->getuid($data);
//            var_dump(json_encode($uid,JSON_UNESCAPED_UNICODE));
            $user = json_decode($uid, true);
            $userinfo = $user['alipay_system_oauth_token_response'];

            if (empty($userinfo['code'])) {
                Session::set('card_user_id', $userinfo['user_id']);
                Session::set('card_access_token', $userinfo['access_token']);
            }
        } else {
//            $callback = 'https://' . $_SERVER ['SERVER_NAME'] . url("carduserali/index", array('mid' => $mid));
            $callback = request()->url(true);
            $url = $aliObj->getOauthRedirect($callback, '', 'auth_base');
            header("Location: $url");
        }

    }

    //获取mid 通过tempalte_id
    private function get_mid($template_id){
        //获取mid
        $CardMemberAli = new CardMemberAli();
        $merchid = $CardMemberAli->where(array('template_id'=>$template_id))->value('mid');
        return $merchid;
    }

    //空操作
    /*
     * 跳转404
     */
    public function _empty(){
        return $this->fetch('public/404');
    }
}
